package com.zahb.qadx.ui.activity.topic;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseSectionQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.luck.picture.lib.tools.ToastUtils;
import com.wang.avi.AVLoadingIndicatorView;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.model.AnswerSheetListBean;
import com.zahb.qadx.model.ExamQuestionsBean;
import com.zahb.qadx.model.UserAnswerBean;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.view.MyDialog;
import com.zahb.qadx.ui.view.PlayDialog;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.Tips;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

//我的考试
public class ExamWillBeginActivity extends BaseActivity implements OnItemChildClickListener {
    @BindView(R.id.countdown)
    TextView countdown;
    @BindView(R.id.first_layout)
    LinearLayout firstLayout;
    @BindView(R.id.test_list_recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.current_qid)
    TextView currentQid;
    @BindView(R.id.the_topic_order)
    TextView theTopicOrder;
    @BindView(R.id.sheet)
    TextView sheet;
    @BindView(R.id.on_a_topic)
    TextView onATopic;
    @BindView(R.id.next_question)
    TextView nextQuestion;
    @BindView(R.id.load_the_film)
    AVLoadingIndicatorView loadTheFilm;
    @BindView(R.id.loading)
    LinearLayout loading;
    @BindView(R.id.submit_prompt)
    TextView submitPrompt;
    private String mSourceId, relationshipId;
    CountDownTimer timer;
    private ExamQuestionsBean mExamQuestionsBean;
    private MultipleItemAdapter mAdapter;
    private List<MyMultipleItem> mDatas02;
    public LinearLayoutManager mLayoutManager;
    private String[] serialNumber = {"A", "B", "C", "D", "E", "F", "G", "H"};
    private String[] theSerialNumber = {"(1) . ", "(2) . ", "(3) . ", "(4) . ", "(5) . ", "(6) . ", "(7) . ", "(8) . ", "(9) . ", "(10) . "};
    private BaseQuickAdapter<UserAnswerBean, BaseViewHolder> mmAdapter;
    // 答题卡
    private MyDialog mMyDialog;
    public RecyclerView answer_sheetr_ecyclerView;
    private BaseSectionQuickAdapter<AnswerSheetListBean, BaseViewHolder> mSheetAdapter;
    private List<AnswerSheetListBean> mExercisesWeeklies;
    private AnswerSheetListBean mExercisesWeekly;
    private EditText short_answer_editText, topic_selection;
    private int count = 0;
    private int countS = 0;
    private PlayDialog mPlayDialog; //重要提示
    private String mForTheRestOf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUnbinder = ButterKnife.bind(this);
        navigationInitialization();//导航栏初始化
        loadTheFilm.show();
        forQuestions();//获取试题
//        importantNote();
        loading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(ExamWillBeginActivity.this, "请稍后", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //获取试题
    private void forQuestions() {
        addDisposable(RetrofitService.getNetService()
                .getForQuestions(mSourceId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        loading.setVisibility(View.GONE);
                        loadTheFilm.hide();
                        mExamQuestionsBean = response.getData();
                        long timeGetTime = new Date().getTime();
                        SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss", Locale.getDefault());
                        String time2 = sdfTwo.format(timeGetTime);
                        mExamQuestionsBean.setOpenTime(time2);
                        mTitle_view.setText(mExamQuestionsBean.getExamName());

                        /**
                         * CountDownTimer timer = new CountDownTimer(3000, 1000)中，
                         * 第一个参数表示总时间，第二个参数表示间隔时间。
                         * 意思就是每隔一秒会回调一次方法onTick，然后1秒之后会回调onFinish方法。
                         */
                        timer = new CountDownTimer(mExamQuestionsBean.getExamTime() * 1000, 1000) {
                            public void onTick(long millisUntilFinished) {
                                countdown.setText("倒计时" + timeParse(millisUntilFinished) + "秒");
                                mForTheRestOf = timeParse(millisUntilFinished) + "秒";
                            }

                            public void onFinish() {
//                                Toast.makeText(ExamWillBeginActivity.this, "结束", Toast.LENGTH_SHORT).show();
                                importantNote(1);
                            }
                        };
                        timer.start();
                        mDatas02 = new ArrayList<>();
                        //这里我是随机给某一条目加载不同的布局
                        for (int i = 0; i < mExamQuestionsBean.getClassIfyList().size(); i++) {
                            if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() == 1) {//单选
                                for (int j = 0; j < mExamQuestionsBean.getClassIfyList().get(i).getQuesList().size(); j++) {
                                    mDatas02.add(new MyMultipleItem(MyMultipleItem.FIRST_TYPE, mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(j)));
                                }
                            } else if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() == 2) {//多选
                                for (int a = 0; a < mExamQuestionsBean.getClassIfyList().get(i).getQuesList().size(); a++) {
                                    mDatas02.add(new MyMultipleItem(MyMultipleItem.SECOND_TYPE, mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(a)));
                                }
                            } else if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() == 3) {//判断
                                for (int a = 0; a < mExamQuestionsBean.getClassIfyList().get(i).getQuesList().size(); a++) {
                                    mDatas02.add(new MyMultipleItem(MyMultipleItem.NORMAL_TYPE, mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(a)));
                                }
                            } else if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() == 4) {//填空
                                for (int a = 0; a < mExamQuestionsBean.getClassIfyList().get(i).getQuesList().size(); a++) {
                                    mDatas02.add(new MyMultipleItem(MyMultipleItem.EMPTY_FOUR, mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(a)));
                                }
                            } else if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() == 5) {//简答
                                for (int a = 0; a < mExamQuestionsBean.getClassIfyList().get(i).getQuesList().size(); a++) {
                                    mDatas02.add(new MyMultipleItem(MyMultipleItem.JANE_FIVE, mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(a)));
                                }
                            } else if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() == 6) {//案例
//                                mDatas02.add(new MyMultipleItem(MyMultipleItem.NORMAL_TYPE, mDailyExaminationQuestionsBean.get(i)));
                            }
                        }
                        //创建布局管理
                        mLayoutManager = new LinearLayoutManager(this);
                        mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                        mRecyclerView.setLayoutManager(mLayoutManager);
                        //创建适配器
                        mAdapter = new MultipleItemAdapter(mDatas02);
                        //给RecyclerView设置适配器
                        mRecyclerView.setAdapter(mAdapter);
                        PagerSnapHelper snapHelper = new PagerSnapHelper();
                        //加在setAdapter后面
                        snapHelper.attachToRecyclerView(mRecyclerView);
                        int count = 0;
                        for (int i = 0; i < mExamQuestionsBean.getClassIfyList().size(); i++) {
                            count = count + mExamQuestionsBean.getClassIfyList().get(i).getQuesList().size();
                        }

                        theTopicOrder.setText("/" + count + "   " + testingTypes(mExamQuestionsBean.getClassIfyList().get(0).getQuestionType()));
                        countS = count;
                        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                            @Override
                            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                                super.onScrollStateChanged(recyclerView, newState);
                                if (newState == 0 && mLayoutManager.findFirstCompletelyVisibleItemPosition() != -1) {
                                    controlTheAnswer(countS, mLayoutManager.findFirstCompletelyVisibleItemPosition() + 1,2);
                                }
                            }
                        });
                    } else {

                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));

    }

    //答题卡
    private void answerSheetList() {

        count = 0;
        View view = getLayoutInflater().inflate(R.layout.answer_sheet_layout, null);
        mMyDialog = new MyDialog(getActivity(), 0, 0, view, R.style.dialog);
        TextView answer_cancel = view.findViewById(R.id.answer_cancel);
        answer_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMyDialog.dismiss();
            }
        });
        answer_sheetr_ecyclerView = view.findViewById(R.id.answer_sheetr_ecyclerView);
        answer_sheetr_ecyclerView.setLayoutManager(new GridLayoutManager(this, 5));
        answer_sheetr_ecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.set(0, 0, 0, 0);
            }
        });

        mExercisesWeeklies = new ArrayList<>();
        //这里我是随机给某一条目加载不同的布局

        for (int i = 0; i < mExamQuestionsBean.getClassIfyList().size(); i++) {
            if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() == 1) {
                sortTheAnswerSheets("单选题", i);
            } else if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() == 2) {
                sortTheAnswerSheets("多选题", i);
            } else if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() == 3) {
                sortTheAnswerSheets("判断题", i);
            } else if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() == 4) {
                sortTheAnswerSheets("填空题", i);
            } else if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() == 5) {
                sortTheAnswerSheets("简答题", i);
            }

        }
        mSheetAdapter = new BaseSectionQuickAdapter<AnswerSheetListBean, BaseViewHolder>(
                R.layout.grouping_layout, R.layout.team_members_layout, mExercisesWeeklies) {
            @Override
            protected void convertHeader(@NotNull BaseViewHolder baseViewHolder, @NotNull AnswerSheetListBean item) {
                TextView text_header = baseViewHolder.findView(R.id.text_header);
                text_header.setText(item.getTitle());
            }

            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, AnswerSheetListBean item) {
                TextView tvName = baseViewHolder.getView(R.id.text_content);
                tvName.setText(item.getQid() + "");


                tvName.setTextColor(getResources().getColor(R.color.white_ffffff));
                if (item.getTheAnswerState() == 0) {
                    tvName.setBackground(getContext().getResources().getDrawable(R.drawable.shape_grey_18dp));

                } else {

                    tvName.setBackground(getContext().getResources().getDrawable(R.drawable.corner22_blue));
                }

                tvName.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        controlTheAnswer(mDatas02.size(), item.getQid(),1);
                        mMyDialog.dismiss();
                    }
                });

            }
        };
        mSheetAdapter.setOnItemChildClickListener(this);
        mSheetAdapter.addChildClickViewIds(R.id.text_content);
        answer_sheetr_ecyclerView.setAdapter(mSheetAdapter);

    }

    //重要提示
    private void importantNote(int mandatory) {
        answerSheetList();
        int donTDo = 0;


        View view = getLayoutInflater().inflate(R.layout.important_note, null);
        mPlayDialog = new PlayDialog(getActivity(), 0, 0, view, R.style.dialog);
        mPlayDialog.setCancelable(false);
        TextView the_clues = view.findViewById(R.id.the_clues);

        for (int i = 0; i < mExercisesWeeklies.size(); i++) {
            if (mExercisesWeeklies.get(i).getGrouping() == 1 && mExercisesWeeklies.get(i).getTheAnswerState() == 0) {
                donTDo++;
            }

        }
        mPlayDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    Toast.makeText(getContext(), "请点击确认交卷", Toast.LENGTH_SHORT).show();
                    return false; //默认返回 false
                }
            }
        });

        TextView continue_dialog = view.findViewById(R.id.continue_dialog);
        TextView return_dialog = view.findViewById(R.id.return_dialog);
        continue_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //交卷
                getSubmitTheTest();
            }
        });
        return_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPlayDialog.dismiss();
            }
        });
        if (mandatory == 1) {// mandatory 0主动交卷 1强制交卷
            return_dialog.setVisibility(View.GONE);
            the_clues.setText("考试时间结束" + "请点击确认交卷!");

        } else {
            the_clues.setText("距离考试结束还有" + mForTheRestOf + "您还有" + donTDo + "题没有答,是否确认交卷!");
        }
        mPlayDialog.show();

    }

    @OnClick({R.id.on_a_topic, R.id.next_question, R.id.sheet})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.on_a_topic://上一题
                if (mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
                    ToastUtils.s(this, "当前是第一道题");
                } else {
                    if (mLayoutManager.findLastCompletelyVisibleItemPosition() == -1) return;
                    controlTheAnswer(mDatas02.size(), mLayoutManager.findFirstCompletelyVisibleItemPosition(),1);
                }
                break;
            case R.id.next_question://下一题
                if (mLayoutManager.findFirstCompletelyVisibleItemPosition() == (mDatas02.size() - 1)) {

                    importantNote(0);

                } else {
                    if (mLayoutManager.findLastCompletelyVisibleItemPosition() == -1) return;

                    controlTheAnswer(mDatas02.size(), mLayoutManager.findFirstCompletelyVisibleItemPosition() + 2,1);
                }
                break;
            case R.id.sheet:
                answerSheetList();//答题卡
                mMyDialog.show_widescreen();
                answer_sheetr_ecyclerView.scrollToPosition(mLayoutManager.findFirstCompletelyVisibleItemPosition());
                break;
        }
    }

    private void getSubmitTheTest() {
        mPlayDialog.dismiss();
        timer.cancel();
        loading.setVisibility(View.VISIBLE);
        submitPrompt.setText("试卷提交中请稍后...");
        loadTheFilm.show();
        if (relationshipId.equals("")) {
            mExamQuestionsBean.setSourceType(1);
        } else {
            mExamQuestionsBean.setRelationshipId(relationshipId);
            mExamQuestionsBean.setSourceType(2);
        }
        mExamQuestionsBean.setTotalQuestion(mDatas02.size());
        Gson gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create();

        for (int i = 0; i < mExamQuestionsBean.getClassIfyList().size(); i++) {
            for (int j = 0; j < mExamQuestionsBean.getClassIfyList().get(i).getQuesList().size(); j++) {
                if (mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(j).getUserAnswer() == null ||mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(j).getUserAnswer().size()==0) {
                    List<UserAnswerBean> userAnswer = new ArrayList<>();
                    mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(j).setUserAnswer(userAnswer);
                }
            }
        }
        String json1 = gson.toJson(mExamQuestionsBean);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json1);
        addDisposable(RetrofitService.getNetService()
                .getSubmitTheTest(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        loadTheFilm.hide();
                        Intent intent = new Intent(ExamWillBeginActivity.this, ResultsPageActivity.class);
                        intent.putExtra("examUserResultId", response.getData().getExamUserResultId() + "");
                        startActivity(intent);
                        finish();
                    }
                }, throwable -> {
                    Tips.RequestError(getActivity());
                    throwable.printStackTrace();
                }));

    }

    private void navigationInitialization() {
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.blue));//状态栏颜色
        mTopBarContainer.setBackgroundColor(getResources().getColor(R.color.blue));//头部布局颜色
        mTitle_view.setTextColor(getResources().getColor(R.color.white));//标题颜色
        Drawable drawable = getResources().getDrawable(R.mipmap.fanhui);//返回箭头
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());// 设置边界
        // param 左上右下
        mTopBarStartText.setCompoundDrawables(drawable, null, null, null);
        mTopBarStartText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Toast.makeText(ExamWillBeginActivity.this, "考试中不可以退出", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_exam_will_begin;
    }

    @Override
    protected void initViews() {
        mSourceId = getIntent().getStringExtra("examId");
        relationshipId = getIntent().getStringExtra("relationshipId");
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.item_name;
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
    }

    public class MultipleItemAdapter extends BaseMultiItemQuickAdapter<MyMultipleItem, BaseViewHolder> {
        public MultipleItemAdapter(List data) {
            super(data);
            //必须绑定type和layout的关系
            addItemType(MyMultipleItem.FIRST_TYPE, R.layout.the_radio);
            addItemType(MyMultipleItem.SECOND_TYPE, R.layout.multi_elect);
            addItemType(MyMultipleItem.NORMAL_TYPE, R.layout.the_radio);
            addItemType(MyMultipleItem.EMPTY_FOUR, R.layout.filiintheblanks_layout);
            addItemType(MyMultipleItem.JANE_FIVE, R.layout.short_answer_layout);
        }

        @Override
        protected void convert(final BaseViewHolder helper, final MyMultipleItem item) {

            switch (helper.getItemViewType()) {
                case MyMultipleItem.FIRST_TYPE://d单选题
                    theRadio(helper, item);
                    break;
                case MyMultipleItem.SECOND_TYPE://多选题
                    multiSelect(helper, item);
                    break;
                case MyMultipleItem.NORMAL_TYPE:

                    theRadio(helper, item);
                    break;
                case MyMultipleItem.EMPTY_FOUR://填空
                    fillInTheBlanks(helper, item);
                    break;
                case MyMultipleItem.JANE_FIVE://简答
                    shortAnswer(helper, item);
                    break;
            }

        }

        //单选
        private void theRadio(BaseViewHolder helper, MyMultipleItem<ExamQuestionsBean.ClassIfyListBean.QuesListBean> item) {
            TextView check_the_parsing = helper.findView(R.id.check_the_parsing);
            check_the_parsing.setVisibility(View.GONE);
            WebView topic_of_dry = helper.findView(R.id.topic_of_dry);//题干
            jsSupport(topic_of_dry, item.getData().getContent());
            RecyclerView recyclerView = helper.findView(R.id.answer_list);//选择列表
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            mmAdapter = new BaseQuickAdapter<UserAnswerBean, BaseViewHolder>(R.layout.choose) {
                @Override
                protected void convert(@NotNull BaseViewHolder baseViewHolder, UserAnswerBean questionOptionListBean) {
                    TextView topic_selection = baseViewHolder.findView(R.id.topic_selection);
                    ImageView selected = baseViewHolder.findView(R.id.selected);
                    TextView the_order = baseViewHolder.findView(R.id.the_order);
                    final LinearLayout linearLayout = baseViewHolder.findView(R.id.the_whole_article);
                    topic_selection.setText(Html.fromHtml(questionOptionListBean.getContent()).toString().trim());
                    the_order.setText(serialNumber[baseViewHolder.getAdapterPosition()]);//顺序ABCD
                    switch (questionOptionListBean.getChoose()) {
                        case 0:
                            topic_selection.setTextColor(getResources().getColor(R.color.colorBlack));
                            the_order.setTextColor(getResources().getColor(R.color.colorBlack));
                            linearLayout.setBackground(getContext().getResources().getDrawable(R.drawable.grey_circle));
                            selected.setVisibility(View.INVISIBLE);

                            break;
                        case 1:
                            topic_selection.setTextColor(getResources().getColor(R.color.blue));
                            the_order.setTextColor(getResources().getColor(R.color.blue));
                            linearLayout.setBackground(getContext().getResources().getDrawable(R.drawable.asingleframe));
                            selected.setVisibility(View.VISIBLE);

                            break;

                    }
                    linearLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            for (int i = 0; i < item.getData().getOptionList().size(); i++) {
                                if (i == baseViewHolder.getAdapterPosition()) {
                                    questionOptionListBean.setChoose(1);
                                    List<UserAnswerBean> userAnswerBeans = new ArrayList<>();
                                    userAnswerBeans.add(questionOptionListBean);
                                    item.getData().setUserAnswer(userAnswerBeans);
                                } else {
                                    item.getData().getOptionList().get(i).setChoose(0);
                                }
                            }
                            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                            mmAdapter.notifyDataSetChanged();
                        }
                    });
                }
            };
            mmAdapter.addData(item.getData().getOptionList());
            recyclerView.setAdapter(mmAdapter);
        }

        //多选
        private void multiSelect(BaseViewHolder helper, MyMultipleItem<ExamQuestionsBean.ClassIfyListBean.QuesListBean> item) {

            TextView check_the_parsing = helper.findView(R.id.check_the_parsing);
            check_the_parsing.setVisibility(View.GONE);
            WebView topic_of_dry = helper.findView(R.id.more_topic_of_dry);//题干
            jsSupport(topic_of_dry, item.getData().getContent());
            RecyclerView recyclerView = helper.findView(R.id.more_answer_list);//选择列表
            TextView more_determine = helper.findView(R.id.more_determine);
            more_determine.setVisibility(View.GONE);
            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
            mmAdapter = new BaseQuickAdapter<UserAnswerBean, BaseViewHolder>(R.layout.choose) {
                @Override
                protected void convert(@NotNull BaseViewHolder baseViewHolder, UserAnswerBean more_questionOptionListBean) {
                    TextView topic_selection = baseViewHolder.findView(R.id.topic_selection);//选项内容
                    ImageView selected = baseViewHolder.findView(R.id.selected);//对号
                    TextView the_order = baseViewHolder.findView(R.id.the_order);//序列号
                    topic_selection.setText(Html.fromHtml(more_questionOptionListBean.getContent()).toString().trim());
                    final LinearLayout linearLayout = baseViewHolder.findView(R.id.the_whole_article);
                    the_order.setText(serialNumber[baseViewHolder.getAdapterPosition()]);//顺序ABCD
                    switch (more_questionOptionListBean.getChoose()) {
                        case 0:
                            topic_selection.setTextColor(getResources().getColor(R.color.colorBlack));
                            the_order.setTextColor(getResources().getColor(R.color.colorBlack));
                            linearLayout.setBackground(getContext().getResources().getDrawable(R.drawable.grey_circle));
                            selected.setVisibility(View.INVISIBLE);

                            break;
                        case 1:
                            topic_selection.setTextColor(getResources().getColor(R.color.blue));
                            the_order.setTextColor(getResources().getColor(R.color.blue));
                            linearLayout.setBackground(getContext().getResources().getDrawable(R.drawable.asingleframe));
                            selected.setVisibility(View.VISIBLE);

                            break;

                    }
                    //多选择
                    linearLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                            if (more_questionOptionListBean.getChoose() == 0) {
                                more_questionOptionListBean.setChoose(1);
                            } else {
                                more_questionOptionListBean.setChoose(0);
                            }
                            List<UserAnswerBean> userAnswerBeans = new ArrayList<>();
                            for (int i = 0; i < item.getData().getOptionList().size(); i++) {
                                if (item.getData().getOptionList().get(i).getChoose() == 1) {
                                    userAnswerBeans.add(item.getData().getOptionList().get(i));
                                }
                            }
                            item.getData().setUserAnswer(userAnswerBeans);
                            recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                            mmAdapter.notifyDataSetChanged();
                        }
                    });
                }
            };
            mmAdapter.addData(item.getData().getOptionList());
            recyclerView.setAdapter(mmAdapter);
        }
    }

    //填空
    private void fillInTheBlanks(BaseViewHolder helper, MyMultipleItem<ExamQuestionsBean.ClassIfyListBean.QuesListBean> item) {
        TextView check_the_parsing = helper.findView(R.id.check_the_parsing);
        check_the_parsing.setVisibility(View.GONE);
        WebView empty_topic_of_dry = helper.findView(R.id.empty_topic_of_dry);
        RecyclerView empty_answer_list = helper.findView(R.id.empty_answer_list);
        jsSupport(empty_topic_of_dry, item.getData().getContent());
        TextView empty_determine = helper.findView(R.id.empty_determine);
        empty_determine.setVisibility(View.GONE);
        empty_answer_list.setLayoutManager(new LinearLayoutManager(getContext()));
        if (item.getData().getUserAnswer() == null|item.getData().getUserAnswer().size()==0) {
            item.getData().setUserAnswer(item.getData().getOptionList());
            for (int i = 0; i < item.getData().getUserAnswer().size(); i++) {
                item.getData().getUserAnswer().get(i).setContent("");
            }
        }
        mmAdapter = new BaseQuickAdapter<UserAnswerBean, BaseViewHolder>(R.layout.fill_in_the_empty_layout) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, UserAnswerBean questionOptionListBean) {

                TextView the_order = baseViewHolder.findView(R.id.the_order);
                topic_selection = baseViewHolder.findView(R.id.topic_selection);
                the_order.setText(theSerialNumber[baseViewHolder.getAdapterPosition()]);
                if (questionOptionListBean.getFillInTheBlanks().equals("")) {
                } else {
                    topic_selection.setText(questionOptionListBean.getFillInTheBlanks());
                }

                topic_selection.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                    }

                    @Override
                    public void afterTextChanged(Editable editable) {
                        questionOptionListBean.setFillInTheBlanks(editable.toString().trim());
                        item.getData().getUserAnswer().get(baseViewHolder.getAdapterPosition()).setContent(editable.toString().trim());

                    }
                });
            }
        };
        mmAdapter.addData(item.getData().getOptionList());
        empty_answer_list.setAdapter(mmAdapter);
    }

    //简答
    private void shortAnswer(BaseViewHolder helper, MyMultipleItem<ExamQuestionsBean.ClassIfyListBean.QuesListBean> item) {
        TextView check_the_parsing = helper.findView(R.id.check_the_parsing);
        check_the_parsing.setVisibility(View.GONE);
        WebView short_answer_topic_of_dry = helper.findView(R.id.short_answer_topic_of_dry);
        jsSupport(short_answer_topic_of_dry, item.getData().getContent());
        short_answer_editText = helper.findView(R.id.short_answer_editText);//输入框
        TextView short_answer_determine = helper.findView(R.id.short_answer_determine);
        short_answer_determine.setVisibility(View.GONE);
        if (item.getData().getUserAnswer() == null||item.getData().getUserAnswer().size()==0) {
            item.getData().setUserAnswer(item.getData().getOptionList());
            for (int i = 0; i < item.getData().getUserAnswer().size(); i++) {
                item.getData().getUserAnswer().get(i).setContent("");
            }
        } else {
            short_answer_editText.setText(item.getData().getUserAnswer().get(0).getContent());
        }
        short_answer_editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                item.getData().getUserAnswer().get(0).setContent(editable.toString().trim());
            }
        });

    }

    /**
     * Android 音乐播放器应用里，读出的音乐时长为 long 类型以毫秒数为单位，例如：将 234736 转化为分钟和秒应为 03:55 （包含四舍五入）
     *
     * @param duration 音乐时长
     * @return
     */
    public static String timeParse(long duration) {
        String time = "";
        long minute = duration / 60000;
        long seconds = duration % 60000;
        long second = Math.round((float) seconds / 1000);
        if (minute < 10) {
            time += "0";
        }
        time += minute + ":";
        if (second < 10) {
            time += "0";
        }
        time += second;
        return time;
    }

    public void jsSupport(WebView webView, String data) {
        webView.setBackgroundColor(0);
        webView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
    }
    @Override
    protected void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }

    //控制选题
    private void controlTheAnswer(int allAnswer, int current ,int   address) {
        hideInput();
        if (short_answer_editText != null) {
            short_answer_editText.clearFocus();
        }


        if (topic_selection != null) {
            topic_selection.clearFocus();
        }
        currentQid.setText(current + "");
        if (current == allAnswer) {
            nextQuestion.setText("完成");
        } else {
            nextQuestion.setText("下一题");
        }
        if (current == 1) {
            onATopic.setVisibility(View.INVISIBLE);
        } else {
            onATopic.setVisibility(View.VISIBLE);
        }
        ExamQuestionsBean.ClassIfyListBean.QuesListBean quesListBean = (ExamQuestionsBean.ClassIfyListBean.QuesListBean) mDatas02.get(current - 1).getData();

        theTopicOrder.setText("/" + allAnswer + "   " + testingTypes(quesListBean.getQuestionType()));
        if (mLayoutManager.findFirstCompletelyVisibleItemPosition() - current > 5 || current - mLayoutManager.findFirstCompletelyVisibleItemPosition() > 5) {
            mRecyclerView.scrollToPosition(current - 1);

        } else {
            if (address==1){
                mRecyclerView.smoothScrollToPosition(current - 1);
            }




        }

    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }

    }

    private String testingTypes(int questionType) {
        switch (questionType) {
            case 1:
                return "单选题";
            case 2:
                return "多选题";
            case 3:
                return "判断题";
            case 4:
                return "填空题";
            case 5:
                return "简答题";
            case 6:
                return "案例题";

        }


        return "试题";
    }

    //答题卡排序
    private void sortTheAnswerSheets(String type, int i) {
        mExercisesWeekly = new AnswerSheetListBean();
        mExercisesWeekly.setGrouping(0);
        mExercisesWeekly.setTitle(type);
        mExercisesWeeklies.add(mExercisesWeekly);
        for (int j = 0; j < mExamQuestionsBean.getClassIfyList().get(i).getQuesList().size(); j++) {
            count++;
            mExercisesWeekly = new AnswerSheetListBean();
            mExercisesWeekly.setQid(count);
            mExercisesWeekly.setGrouping(1);
            if (mExamQuestionsBean.getClassIfyList().get(i).getQuestionType() > 3) {
                if (mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(j).getUserAnswer() != null) {
                    for (int k = 0; k < mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(j).getUserAnswer().size(); k++) {
                        if (mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(j).getUserAnswer().get(k).getContent().equals("")) {
                        } else {
                            mExercisesWeekly.setTheAnswerState(1);
                        }
                    }
                }
            } else {
                mExercisesWeekly.setTheAnswerState(mExamQuestionsBean.getClassIfyList().get(i).getQuesList().get(j).getUserAnswer() != null ? 1 : 0);
            }
            mExercisesWeeklies.add(mExercisesWeekly);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Toast.makeText(this, "考试中不可以退出", Toast.LENGTH_SHORT).show();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
}
